<template>
    <div class="app-container">
        <vxe-grid ref="xGrid" v-bind="gridOptions" @checkbox-change="handleSelectionChange" @edit-actived="editActivedEvent" :data="columnData">
            <template #toolbar_buttons>
                <el-row :gutter="10">
                    <el-col :span="1.5">
                        <el-button type="info" plain icon="Plus" @click="handleAdd">新增</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
                    </el-col>
                </el-row>
            </template>
            <template #slotsColumnField="{ row }">
                <vxe-input v-model="row.field" :disabled="disabledField"></vxe-input>
            </template>
        </vxe-grid>
    </div>
</template>

<script setup name="GenEdit" lang="ts">
    import { getCurrentInstance, ref, reactive, unref } from "vue";
    import { useRoute } from "vue-router";
    import useBaseApi from "@/api/base/index";
    import { VxeGridInstance, VxeGridProps, VxeGridListeners, VxeGridEvents, GridMethods, TableMethods, TableEditMethods, TableValidatorMethods } from "../../../../../types/all";
    import { generateBaseFunc } from "@/utils/common";
    import { gridComponentMethodKeys } from "@/components/ElementRender/src/methods";
    import XEUtils from "xe-utils";
    import { optionselect as getDictOptionselect } from "@/api/system/dict/type";
    defineProps({
        columnData: {
            type: Array,
        },
    });
    const route = useRoute();
    const { proxy } = getCurrentInstance() as any;
    const { callRemoves } = useBaseApi("/tableConfig/menuColumn");
    const tableHeight = ref(document.documentElement.scrollHeight - 257 + "px");
    const multiple = ref(true);
    const tableId = ref(route.params.tableId);
    const xGrid = ref({} as VxeGridInstance);
    function getTableAction() {
        const tableAction = unref(xGrid);
        if (!tableAction) {
            throw new Error("tableAction is null");
        }
        return tableAction;
    }
    const dictOptions = ref<any>([]);
    /** 查询字典下拉列表 */
    const dictData = await getDictOptionselect();
    dictOptions.value = dictData.data;

    const gridOptions = reactive<VxeGridProps>({
        border: true,
        resizable: true,
        showHeaderOverflow: true,
        showOverflow: true,
        highlightHoverRow: true,
        keepSource: true,
        id: "17",
        height: tableHeight,
        sortConfig: {
            trigger: "cell",
            remote: true,
        },
        filterConfig: {
            remote: true,
        },
        pagerConfig: {
            pageSize: 10,
            pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000],
            perfect: true,
            enabled: false,
        },
        toolbarConfig: {
            refresh: true,
            zoom: true,
            custom: true,
            slots: {
                buttons: "toolbar_buttons",
            },
        },
        columns: [
            {
                type: "checkbox",
                width: 50,
                fixed: "left",
            },
            {
                field: "columnId",
                title: "序号",
                width: 80,
                fixed: "left",
            },
            {
                field: "sortNo",
                title: "排序",
                width: 100,
                editRender: {
                    name: "$input",
                    props: {
                        type: "number",
                    },
                    attrs: { placeholder: "请输入排序" },
                },
            },
            {
                field: "columnName",
                title: "列名称",
                width: 140,
                fixed: "left",
            },
            {
                field: "columnComment",
                title: "列描述",
                width: 140,
                fixed: "left",
            },
            {
                field: "field",
                title: "字段",
                width: 140,
                editRender: { enabled: true },
                slots: { edit: "slotsColumnField" },
                fixed: "left",
            },
            {
                field: "title",
                title: "字段名",
                width: 140,
                editRender: {
                    name: "input",
                    attrs: { placeholder: "请输入字段名" },
                },
                fixed: "left",
            },
            {
                field: "isIgnore",
                title: "是否显示",
                width: 120,
                titlePrefix: { message: "在表格和自定义表格列表中是否可见" },
                editRender: {
                    name: "ElSwitch",
                    props: {
                        activeValue: true,
                        inactiveValue: false,
                    },
                },
            },
            {
                field: "visible",
                title: "是否可视",
                width: 120,
                titlePrefix: { message: "在表格中隐藏，可通过自定义表格显示" },
                editRender: {
                    name: "ElSwitch",
                    props: {
                        activeValue: true,
                        inactiveValue: false,
                    },
                },
            },
            {
                field: "sortable",
                title: "是否排序",
                width: 120,
                editRender: {
                    name: "ElSwitch",
                    props: {
                        activeValue: true,
                        inactiveValue: false,
                    },
                },
            },
            {
                field: "resizable",
                title: "列宽拖拽",
                width: 120,
                editRender: {
                    name: "ElSwitch",
                    props: {
                        activeValue: true,
                        inactiveValue: false,
                    },
                },
            },
            {
                field: "align",
                title: "列对齐方式",
                width: 120,
                editRender: {
                    name: "select",
                    options: [
                        {
                            value: "left",
                            label: "左对齐",
                        },
                        {
                            value: "center",
                            label: "居中对齐",
                        },
                        {
                            value: "right",
                            label: "右对齐",
                        },
                    ],
                },
            },
            {
                field: "width",
                title: "宽度",
                width: 120,
                titlePrefix: { message: "类型（number）" },
                editRender: { name: "input", attrs: { placeholder: "请输入宽度" } },
            },
            {
                field: "minWidth",
                title: "最小宽度",
                width: 120,
                titlePrefix: { message: "类型（number）" },
                editRender: { name: "input", attrs: { placeholder: "请输入宽度" } },
            },
            {
                field: "type",
                title: "列类型",
                width: 120,
                editRender: {
                    name: "select",
                    options: [
                        {
                            value: "",
                            label: "",
                        },
                        {
                            value: "seq",
                            label: "序号",
                        },
                        {
                            value: "checkbox",
                            label: "复选框",
                        },
                        {
                            value: "radio",
                            label: "单选框",
                        },
                        {
                            value: "expand",
                            label: "展开行",
                        },
                        {
                            value: "html",
                            label: "HTML 标签",
                        },
                    ],
                },
            },
            {
                field: "fixed",
                title: "列固定",
                width: 120,
                editRender: {
                    name: "select",
                    options: [
                        {
                            value: "",
                            label: "",
                        },
                        {
                            value: "left",
                            label: "固定左侧",
                        },
                        {
                            value: "right",
                            label: "固定右侧",
                        },
                    ],
                },
            },
            {
                field: "headerAlign",
                title: "表头列的对齐方式",
                width: 155,
                editRender: {
                    name: "select",
                    options: [
                        {
                            value: "left",
                            label: "左对齐",
                        },
                        {
                            value: "center",
                            label: "居中对齐",
                        },
                        {
                            value: "right",
                            label: "右对齐",
                        },
                    ],
                },
            },
            {
                field: "footerAlign",
                title: "表尾列的对齐方式",
                width: 155,
                editRender: {
                    name: "select",
                    options: [
                        {
                            value: "left",
                            label: "左对齐",
                        },
                        {
                            value: "center",
                            label: "居中对齐",
                        },
                        {
                            value: "right",
                            label: "右对齐",
                        },
                    ],
                },
            },
            {
                field: "showOverflow",
                title: "内容过长时显示",
                width: 140,
                editRender: {
                    name: "select",
                    options: [
                        {
                            value: "ellipsis",
                            label: "显示省略号",
                        },
                        {
                            value: "title",
                            label: "原生title",
                        },
                        {
                            value: "tooltip",
                            label: "tooltip提示",
                        },
                    ],
                },
            },
            {
                field: "showHeaderOverflow",
                title: "表头内容过长时显示",
                width: 167,
                editRender: {
                    name: "select",
                    options: [
                        {
                            value: "ellipsis",
                            label: "只显示省略号",
                        },
                        {
                            value: "title",
                            label: "原生 title",
                        },
                        {
                            value: "tooltip",
                            label: "tooltip提示",
                        },
                    ],
                },
            },
            {
                field: "showFooterOverflow",
                title: "表尾内容过长时显示",
                width: 167,
                editRender: {
                    name: "select",
                    options: [
                        {
                            value: "ellipsis",
                            label: "只显示省略号",
                        },
                        {
                            value: "title",
                            label: "原生 title",
                        },
                        {
                            value: "tooltip",
                            label: "tooltip提示",
                        },
                    ],
                },
            },
            {
                field: "slots",
                title: "插槽",
                width: 223,
                editRender: { name: "MonacoEditor", attrs: { placeholder: "请输入" }, props: { title: "插槽", language: "json" } },
            },
            {
                field: "filters",
                title: "配置筛选条件",
                width: 223,
                editRender: { name: "MonacoEditor", attrs: { placeholder: "请输入" }, props: { title: "配置筛选条件" } },
            },
            {
                field: "filterMultiple",
                title: "只对 filters 有效，筛选是否允许多选",
                width: 160,
                editRender: {
                    name: "ElSwitch",
                    props: {
                        activeValue: true,
                        inactiveValue: false,
                    },
                },
            },
            {
                field: "filterMethod",
                title: "只对 filters 有效，列的筛选方法，该方法的返回值用来决定该行是否显示",
                width: 223,
                editRender: { name: "MonacoEditor", attrs: { placeholder: "请输入" }, props: { title: "只对 filters 有效，列的筛选方法，该方法的返回值用来决定该行是否显示" } },
            },
            {
                field: "filterResetMethod",
                title: "只对 filters 有效，自定义筛选重置方法",
                width: 223,
                editRender: { name: "MonacoEditor", attrs: { placeholder: "请输入" }, props: { title: "只对 filters 有效，自定义筛选重置方法" } },
            },
            {
                field: "filterRecoverMethod",
                title: "只对 filters 有效，自定义筛选复原方法（使用自定义筛选时可能会用到）",
                width: 223,
                editRender: { name: "MonacoEditor", attrs: { placeholder: "请输入" }, props: { title: "只对 filters 有效，自定义筛选复原方法（使用自定义筛选时可能会用到）" } },
            },
            {
                field: "filterRender",
                title: "筛选渲染器配置项",
                width: 223,
                editRender: { name: "MonacoEditor", attrs: { placeholder: "请输入" }, props: { title: "筛选渲染器配置项" } },
            },
            {
                field: "exportMethod",
                title: "自定义单元格数据导出方法，返回自定义",
                width: 223,
                editRender: { name: "MonacoEditor", attrs: { placeholder: "请输入" }, props: { title: "自定义单元格数据导出方法，返回自定义" } },
            },
            {
                field: "footerExportMethod",
                title: "自定义表尾单元格数据导出方法，返回自定义的值",
                width: 223,
                editRender: { name: "MonacoEditor", attrs: { placeholder: "请输入" }, props: { title: "自定义表尾单元格数据导出方法，返回自定义的值" } },
            },
            {
                field: "titlePrefix",
                title: "标题前缀图标配置项",
                width: 223,
                editRender: { name: "MonacoEditor", attrs: { placeholder: "请输入" }, props: { title: "标题前缀图标配置项" } },
            },
            {
                field: "cellRender",
                title: "默认的渲染器配置项",
                width: 223,
                editRender: { name: "MonacoEditor", attrs: { placeholder: "请输入" }, props: { title: "默认的渲染器配置项", language: "json" } },
            },
            {
                field: "editRender",
                title: "可编辑渲染器配置项",
                width: 223,
                editRender: { name: "MonacoEditor", attrs: { placeholder: "请输入" }, props: { title: "可编辑渲染器配置项", language: "json" } },
            },
            {
                field: "contentRender",
                title: "内容渲染配置项",
                width: 223,
                editRender: { name: "MonacoEditor", attrs: { placeholder: "请输入" }, props: { title: "内容渲染配置项", language: "json" } },
            },
            {
                field: "dictType",
                title: "字典类型",
                width: 140,
                editRender: {
                    name: "$select",
                    options: dictOptions.value,
                    optionProps: { value: "dictType", label: "dictDescribe" },
                    props: {
                        filterable: true,
                        clearable: true,
                        multiple: true,
                    },
                },
            },
            {
                field: "colId",
                title: "自定义列的唯一主键",
                width: 170,
                editRender: { name: "input", attrs: { placeholder: "请输入" } },
            },
            {
                field: "className",
                title: "单元格附加className",
                width: 181,
                editRender: { name: "MonacoEditor", attrs: { placeholder: "请输入" }, props: { title: "单元格附加className" } },
            },
            {
                field: "headerClassName",
                title: "表头的单元格附加className",
                width: 223,
                editRender: { name: "MonacoEditor", attrs: { placeholder: "请输入" }, props: { title: "表头的单元格附加className" } },
            },
            {
                field: "footerClassName",
                title: "表尾的单元格附加className",
                width: 223,
                editRender: { name: "MonacoEditor", attrs: { placeholder: "请输入" }, props: { title: "表尾的单元格附加className" } },
            },
            {
                field: "formatter",
                title: "格式化显示内容",
                width: 140,
                editRender: { name: "MonacoEditor", attrs: { placeholder: "请输入" }, props: { title: "格式化显示内容" } },
            },
            {
                field: "sortBy",
                title: "指定排序的字段",
                width: 140,
                editRender: { name: "input", attrs: { placeholder: "请输入" } },
            },
            {
                field: "sortType",
                title: "排序的字段类型",
                width: 140,
                editRender: {
                    name: "select",
                    options: [
                        {
                            value: "auto",
                            label: "auto",
                        },
                        {
                            value: "number",
                            label: "number",
                        },
                        {
                            value: "string",
                            label: "string",
                        },
                    ],
                },
            },
            {
                field: "ext_params",
                title: "额外参数",
                width: 120,
                editRender: { name: "MonacoEditor", attrs: { placeholder: "请输入" }, props: { title: "额外参数" } },
            },
            {
                field: "treeNode",
                title: "是否为树节点",
                width: 130,
                cellRender: {
                    name: "$switch",
                    props: {
                        openValue: 1,
                        closeValue: 0,
                    },
                },
                slots: {
                    default: "slotItreeNode",
                },
            },
            {
                field: "remark",
                title: "备注",
                width: 150,
                editRender: { name: "input", attrs: { placeholder: "请输入备注" } },
            },
        ],
        editConfig: {
            trigger: "click",
            mode: "row",
            showStatus: true,
        },
        editRules: {
            field: [{ required: true, message: "字段必须填写" }],
            title: [{ required: true, message: "字段名称必须填写" }],
        },
    });

    const disabledField = ref(false);
    const editActivedEvent: VxeGridEvents.EditDisabled = ({ row }: any) => {
        disabledField.value = null != row["field"];
    };

    /** 多选框选中数据 */
    function handleSelectionChange(data: any) {
        multiple.value = !data.records.length;
    }
    /**新增 */
    function handleAdd() {
        xGrid.value.commitProxy("insert").then(({ row }: any) => {
            row["tableId"] = Number(tableId.value);
            row["columnId"] = null;
            row["ignore"] = 1;
            row["visible"] = 1;
            row["sortable"] = 1;
            row["resizable"] = 1;
            row["editRender"] = '{"name": "$input","enabled": false,"props": {},"options": [],"optionProps": [],"optionGroups": [],"optionGroupProps": "","events": "","content": "","autofocus": "","autoselect": "","defaultValue": "","immediate": "","placeholder": ""}';
            xGrid.value.setEditRow(row);
        });
    }
    /**删除 */
    async function handleDelete() {
        const { rows } = await xGrid.value.removeCheckboxRow();
        const deleteIds = ref([]);
        XEUtils.arrayEach(rows, (item: any) => {
            if (item["columnId"]) {
                deleteIds.value.push(item["columnId"]);
            }
        });
        if (deleteIds.value.length > 0) {
            callRemoves(deleteIds.value.join(","));
        }
    }

    function getFormPromise(form: any) {
        return new Promise((resolve: any) => {
            form.validate((res: any) => {
                resolve(res);
            });
        });
    }
    const extendTableMethods = (methodKeys: any) => {
        const funcs: any = {};
        methodKeys.forEach((name: any) => {
            funcs[name] = (...args: any[]) => {
                const $vxegrid: any = xGrid.value;
                if ($vxegrid && $vxegrid[name]) {
                    return $vxegrid[name](...args);
                }
            };
        });
        return funcs;
    };
    const getColumnData = () => {
        console.log("列配置", getTableAction().getTableData());
        return getTableAction().getTableData();
    };

    const gridExtendTableMethods = extendTableMethods(gridComponentMethodKeys) as GridMethods & TableMethods & TableEditMethods & TableValidatorMethods;
    defineExpose({
        ...gridExtendTableMethods,
        getColumnData,
    });
</script>
